<template>
	<div>
		<div id="UserEdit">
			<el-collapse>
                <!--编辑个人资料-->
				<el-collapse-item title="编辑个人资料" name="1">
					<el-form  ref="dataFrom" :model="dataFrom" :rules="dataFromRules" label-width="100px" class="demo-ruleForm">
						<el-form-item label="姓名" prop="pass">
							<el-input v-model="dataFrom.userName" autocomplete="off" style="width:200px;"></el-input>
						</el-form-item>
						<el-form-item label="用户名" prop="checkPass">
							<el-input v-model="dataFrom.loginName" autocomplete="off" style="width:200px;" :disabled="true"></el-input>
						</el-form-item>
						<el-form-item label="生日" prop="checkPass">
							<el-date-picker
							v-model="dataFrom.birthday"
							type="date"
							placeholder="选择日期">
							</el-date-picker>
						</el-form-item>
						<el-form-item label="性别" prop="checkPass">
							<el-select v-model="dataFrom.sex" clearable placeholder="请选择">
								<el-option
								v-for="item in options"
								:key="item.id"
								:label="item.label"
								:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="updateUser()">提交</el-button>
							<el-button @click="resetForm('ruleForm')">重置</el-button>
						</el-form-item>
					</el-form>
				</el-collapse-item>
                <!--上传头像-->
				<el-collapse-item title="上传头像" name="2">
					<el-card class="box-card1">
						<div class="box-card">
						<el-upload
							class="avatar-uploader"
							action="http://127.0.0.1:8082/uploadPicture"
							:show-file-list="false"
							:on-success="handleAvatarSuccess"
							:before-upload="beforeAvatarUpload">
							<img v-if="imageUrl" :src="imageUrl" class="avatar">
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
                        <el-button type="primary" @click="updateAvatar()" style="margin-left:55px;margin-top:10px;">提交</el-button>
						</div>
					</el-card>
				</el-collapse-item>
                <!--绑定/更改手机号-->
				<el-collapse-item title="绑定/更改手机号" name="3">
                <el-form  ref="dataFrom" :model="dataFrom" :rules="dataFromRules" label-width="100px" class="demo-ruleForm">
					<el-form-item label="输入手机号" prop="iphone">
					<el-input v-model="dataFrom.iphone" autocomplete="off" style="width:300px;"></el-input>
                    <el-button type="primary" @click="updatePhone()">提交</el-button>
                    </el-form-item>
                </el-form>    
				</el-collapse-item>
                <!--绑定/更改邮箱-->
				<el-collapse-item title="绑定/更改邮箱" name="4">
                 <el-form  ref="dataFrom" :model="dataFrom" :rules="dataFromRules" label-width="100px" class="demo-ruleForm">
					<el-form-item label="输入邮箱" prop="mail">
					<el-input v-model="dataFrom.mail" autocomplete="off" style="width:300px;"></el-input>
                    <el-button type="primary" @click="updateMail()">提交</el-button>
                    </el-form-item>
                </el-form>    
				</el-collapse-item>
			</el-collapse>
		</div>
	</div>
</template>
<script>

const axios = require('axios')
export default {
	data () {
		// 验证方法
        let validatorPhone = function (phone, value, callback) {
            //验证手机号的正则表达式
            let reg=/^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/
            if (value !== '') {
                if (!reg.test(value)) {
                    callback(new Error('输入正确手机号'))
                } else {
                    callback()
                }
            } else {
				callback(new Error('手机号不能为空'))
            }
        }
        /* 校验邮箱 */
        var validateEmail = (rule, value, callback) => {
            const data = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/;
            if (!value) {
                return callback(new Error('邮箱不能为空!!'))
            }
            setTimeout(() => {
                if (!data.test(value)) {
                    return callback(new Error('邮箱格式错误'))
                } else {
                    callback()
                }
            }, 100)
        }
		return{
            //用户信息数组.
			dataFrom:{
				id: '',
				userName: '',
				loginName: '',
				password: '',
				birthday: '',
				sex: '',
				iphone: '',
				mail: '',
                avatarId: ''
			},
            // 用户新增校验
            dataFromRules: {
                // 手机号验证
                iphone: [
                    { validator: validatorPhone, trigger: 'blur'},
                ],
                mail: [
                    { validator: validateEmail, trigger: 'blur'},
                ],
            },
            //性别选择框
			options: [{
				id: 1,
				label: '男'
			}, {
				id: 2,
				label: '女'
			}],
            //图片大小
			imageFile:File,
            //图片路径
			imageUrl: '',
            //接收用户信息集合
			userList: []
		}
	},
	mounted () {
		//获取页头用户数据id
		this.dataFrom.id = window.sessionStorage.getItem('id')
		//获取页头用户数据loginName
    	this.dataFrom.loginName = window.sessionStorage.getItem('loginName')
        //初始化用户查询并回显方法
		this.getQueryUserList()
	},
	methods: {
        //图片上传
		handleAvatarSuccess (res, file) {
      		this.imageUrl = URL.createObjectURL(file.raw)
		},
		beforeAvatarUpload (file) {
			const isJPG = file.type === 'image/jpeg'
			const isLt2M = file.size / 1024 / 1024 < 2
			if (!isJPG) {
				this.$message.error('上传头像图片只能是 JPG 格式!')
			}
			if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!')
			}
			this.imageFile = file
			this.imageUrl = URL.createObjectURL(file)
			return false
		},
        //时间重新定义格式//编辑时回显用该方法this.StrToGMT('2020-10-27 09:23')转换成Tue Oct 27 2020 09:23:00 GMT+0800 
        StrToGMT(time) {
            let GMT = new Date(time);
            return GMT;
        },
        //时间重新定义格式//编辑时回显用该方法this.dateValue Oct 27 2020 09:23:00 GMT+0800 转换成('2020-10-27 09:23')
        dateValue(time) {
            let d = new Date(time);
            const resDate =
                d.getFullYear() +
                "-" +
                this.monthOrDay(d.getMonth() + 1) +
                "-" +
                this.monthOrDay(d.getDate()) +
                " " +
                this.monthOrDay(d.getHours()) +
                ":" +
                this.monthOrDay(d.getMinutes());
            return resDate;
        },
		//查询用户信息并回显
        getQueryUserList(){
            axios.get('http://127.0.0.1:8082/user/getQueryUserList?id=' + this.dataFrom.id).then(res=>{
                this.dataFrom.userList = res.data.obj
				this.dataFrom.userName = res.data.obj[0].userName
				this.dataFrom.birthday = res.data.obj[0].birthday
				this.dataFrom.sex = res.data.obj[0].sex
				this.dataFrom.iphone = res.data.obj[0].phone
				this.dataFrom.mail = res.data.obj[0].mail
                this.dataFrom.avatarId = res.data.obj[0].avatarId
                //初始化头像
                this.selectAvatarId()
            }).catch(error => {
                this.$message.error('查询用户失败！');
            })
        },
        //修改个人信息
		updateUser(){
			var formdata = new FormData()
			formdata.set("userName", this.dataFrom.userName)
			formdata.set("birthday", this.StrToGMT(this.dataFrom.birthday))
			formdata.set("sex", this.dataFrom.sex)
			formdata.set("id",window.sessionStorage.getItem('id'))
			axios.post('http://127.0.0.1:8082/user/updateUser', formdata)
			.then(res => {
				if (res.data.obj > 0) {
					this.message('恭喜你，修改信息成功！', 'success')
                    //初始化方法
		            this.getQueryUserList()
				} else {
					this.message('对不起，保存失败！', 'warning')
				}
			})
		},
        //查询用户头像
        selectAvatarId(){
            this.imageUrl = 'http://127.0.0.1:8082/getImageById?id='+ this.dataFrom.avatarId
        },
        //绑定/更改头像
        updateAvatar(){
			var formdata = new FormData()
			formdata.set("id",window.sessionStorage.getItem('id'))
            if(this.imageFile.name!="File"){
                formdata.set("file",this.imageFile,this.imageFile.name)
            }
			axios.post('http://127.0.0.1:8082/user/updateUserAratar', formdata)
			.then(res => {
				if (res.data.obj > 0) {
					this.message('恭喜你，修改信息成功！', 'success')
                    //初始化方法
		            this.getQueryUserList()
				} else {
					this.message('对不起，保存失败！', 'warning')
				}
			})
		},
        //  绑定/更改手机号
        updatePhone(){
			var formdata = new FormData()
			formdata.set("id",window.sessionStorage.getItem('id'))
            formdata.set("phone",this.dataFrom.iphone)
			axios.post('http://127.0.0.1:8082/user/updateUserPhone', formdata)
			.then(res => {
                debugger
				if (res.data.obj > 0) {
					this.message('恭喜你，修改信息成功！', 'success')
                    //初始化方法
		            this.getQueryUserList()
				} else {
					this.message('对不起，保存失败！', 'warning')
				}
			})
		},
        // 绑定 / 更改邮箱
        updateMail(){
			var formdata = new FormData()
			formdata.set("id",window.sessionStorage.getItem('id'))
            formdata.set("mail",this.dataFrom.mail)
			axios.post('http://127.0.0.1:8082/user/updateUserMail', formdata)
			.then(res => {
                debugger
				if (res.data.obj > 0) {
					this.message('恭喜你，修改信息成功！', 'success')
                    //初始化方法
		            this.getQueryUserList()
				} else {
					this.message('对不起，保存失败！', 'warning')
				}
			})
		},
        //信息弹窗
        message (message, type) {
			this.$message({
				message: message,
				type: type
			})
		}
	}
}
</script>
<style scoped>
  #UserEdit{
	  width:100%;
      margin: 0 auto;
  }
  #UserEdit1{
	  height: 20px;
	   border: 2px solid #ccc;
  }
  .cardSize{
      width: 1200px;
  }

  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  .box-card {
    width: 180px;
    height: 180px;
    margin: 0 auto;
    margin-top: 20px;
	border: 1px solid  #ccc;
  }
  .box-card1 {
    width: 800px;
    height: 300px;
    margin: 0 auto;
    margin-top: 20px;
  }
  .avatar-uploader .el-upload {
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader{
    text-align: center;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    width: 100%;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
  }
</style>